#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")

#include "Display.hpp"

#include <gl/gl.h>
#include <gl/glu.h>
#include <math.h>

Display::Display()
{

}

Display::~Display()
{
}

bool Display::OpenDisplay()
{
     PIXELFORMATDESCRIPTOR descriptor;
     memset( &descriptor, 0, sizeof( descriptor ) );
     descriptor.nVersion = 1;
     descriptor.nSize = sizeof( PIXELFORMATDESCRIPTOR );
     descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
     descriptor.iPixelType = PFD_TYPE_RGBA;
     descriptor.cColorBits = 32;
     descriptor.cDepthBits = 16;
     descriptor.iLayerType = PFD_MAIN_PLANE;

     mDevice = GetDC( mWindow );
     if( !mDevice )
        return false;

     GLuint format = ChoosePixelFormat( mDevice, &descriptor );
     if( !format )
        return false;

     if( !SetPixelFormat( mDevice, format, &descriptor ) )
        return false;

     mContext = wglCreateContext( mDevice );
     if( !mContext )
        return false;

     if( !wglMakeCurrent( mDevice, mContext ) )
        return false;

     ShowWindow( mWindow, SW_NORMAL );

     glMatrixMode(GL_PROJECTION);
     //glLoadIdentity();

     GLfloat zNear = 0.1f;
     GLfloat zFar = 255.0f;
     GLfloat aspect = static_cast< GLfloat >( DISPLAY_WIDTH ) / static_cast< GLfloat >( DISPLAY_HEIGHT );
     GLfloat fH = tan( static_cast< GLfloat >( FIELD_OF_VIEW / 360.0f * 3.14159f ) ) * zNear;
     GLfloat fW = fH * aspect;
     glFrustum( -fW, fW, -fH, fH, zNear, zFar );

     glMatrixMode(GL_MODELVIEW);
     glLoadIdentity();

     glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
     glEnable(GL_DEPTH_TEST);
     glEnable(GL_POINT_SMOOTH);
     glPointSize(4);

     return true;
}

void Display::CloseDisplay()
{	
     ReleaseDC( mWindow, mDevice );
     mDevice = 0;

     DestroyWindow( mWindow );
     mWindow = 0;
}

void Display::SetDisplayWindow( HWND window )
{
     mWindow = window;
}

const HDC & Display::GetDisplayDevice()
{
     return mDevice;
}

HWND Display::GetDisplayWindow()
{
	return mWindow;
}

bool Display::GetDisplayIsActive()
{
	return mActive;
}